<!--
 * @Description: 组织人员-指定上级
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-04-23
-->
<template>
  <div class="leader">
    <a-modal v-model:visible="visible" title="指定上级" :footer="null" :width="700">
      <div class="title">{{ props.data.userName }}的上级：{{ props.data.userLeaderName || '--' }}</div>
      <div class="search">
        <a-row :gutter="24">
          <a-col :span="9">
            <a-form-item label="姓名">
              <a-input v-model:value="searchParam.userName" placeholder="请输入" />
            </a-form-item>
          </a-col>
          <a-col :span="9">
            <a-form-item label="组织架构">
              <a-tree-select v-model:value="searchParam.deptId" :tree-data="deptOptions" allow-clear :show-checked-strategy="TreeSelect.SHOW_PARENT" placeholder="请选择" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-button type="primary" @click="search()">查询</a-button>
          </a-col>
        </a-row>
      </div>
      <div class="list">
        <a-table :columns="columns" :data-source="dataList" :loading="loading" :pagination="pagination" @change="onPaginationChange">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <span>
                <a-popconfirm title="是否要设为上级?" ok-text="是" cancel-text="否" @confirm="setLeader(record)">
                  <a>设为上级</a>
                </a-popconfirm>
              </span>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { message, TreeSelect } from 'ant-design-vue'
  import { computed, reactive, watch } from 'vue'

  import { requestAddUserLeader, requestUserCompanyList } from '/@/api/business/company/dept'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { useQueryPagination } from '/@/hooks/useQueryPagination'
  import { getCompanyInfo } from '/@/storage'
  import { convertDeepOptions } from '/@/utils/org'

  const { companyId } = getCompanyInfo()

  const props = defineProps({
    visible: { type: Boolean, default: false },
    depts: { type: Array, default: () => [] },
    data: { type: Object, default: () => ({}) as UserDeptListTypes.IResponse },
  })

  const emits = defineEmits(['update:visible', 'success'])

  const visible = computed({
    get: () => props.visible,
    set: (val: boolean) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) initData()
    },
  )

  /** 查询条件 */
  const searchParam = reactive<UserCompanyListTypes.IRequest>({
    companyId,
    userName: '',
    deptId: undefined,
  })

  /** 组织架构-选项 */
  const deptOptions = computed(() => convertDeepOptions(props.depts))

  /** 表格列配置 */
  const columns = [
    { title: '姓名', dataIndex: 'userName', customRender: ({ record }) => record.userName || '--' },
    {
      title: '所在部门',
      dataIndex: 'userPhone',
      customRender: ({ record }) => {
        if (record.positionNames.length === 0) return '--'
        return record.positionNames.map((item) => item.positionName).join('，')
      },
    },
    {
      title: '岗位',
      dataIndex: 'positionNames',
      customRender: ({ record }) => {
        if (record.depts.length === 0) return '--'
        return record.depts.map((item) => item.deptName).join('，')
      },
    },
    { title: '操作', key: 'action' },
  ]

  /** 表格分页hook */
  const { loading, queryList, dataList, pagination, onPaginationChange } = useQueryPagination<UserCompanyListTypes.IRequest, UserCompanyListTypes.IResponse[]>(searchParam, requestUserCompanyList)

  /**
   * 初始化数据
   */
  const initData = () => queryList()

  /**
   * 查询
   */
  const search = () => queryList({ current: 1 })

  /**
   * 设为上级
   * @param record 组织人员
   */
  const setLeader = async (record: UserCompanyListTypes.IResponse) => {
    const { responseCode } = await requestAddUserLeader({
      companyId,
      leaderUserId: record.userId,
      deptId: record.depts[0].deptId,
      userId: props.data.userId,
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('设置成功')
      visible.value = false
      emits('success')
    }
  }
</script>

<style lang="less" scoped>
  .title {
    position: relative;
    top: -12px;
  }

  .search {
    margin-top: 12px;
  }

  .list {
    height: 450px;
    overflow: auto;
  }
</style>
